package server_commands;

import static server.RLM_Server.activeConnections;

import java.sql.SQLException;
import java.util.StringTokenizer;
import java.util.Vector;

import server.ServerSocketConnection;
import utils.GenerateID;
import connection_modul.DatabaseConnection;

public class BLOCKCommand extends Command {
	
	
	public BLOCKCommand(String parameter) {
		setCode(BLOCK_CMD);
		setParameter(parameter);
	}
	
	/**
	 * Metoda ubacuje blokiranog korisnika u odgovarajucu tabelu u bazi, proverava da li je
	 * status blokiranog korisnika offline i, ukoliko nije, obavestava ga o, uslovno receno,
	 * novom statusu (offline) korisnika koji ga je blokirao.
	 * 
	 * @param connection - konekcija ka klijentu
	 * @param dbConnection - objekat za rad sa bazom
	 * 
	 */
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {
		
		StringTokenizer tokenizer = new StringTokenizer(getParameter());
		
		String username = tokenizer.nextToken();
		String blockedUser = tokenizer.nextToken();
		
		String updateSQLQuery = "INSERT INTO tblBlocks (block_id, user_source, user_dest)" +				
			 " VALUES (" + GenerateID.generateID() + ", '" + username + "', '" + blockedUser + "')";
		
		try {
			dbConnection.doUpdateStatement(updateSQLQuery);
			
			String selectSQLQuery = "SELECT tblUsers.nickname, tblUsers.email, tblUsers.avatar " +
				"FROM tblUsers " +
				"WHERE tblUsers.username = '" + username + "'";
			
			dbConnection.doStatement(selectSQLQuery);
			
			ServerSocketConnection tempConnection = activeConnections.get(blockedUser);
			
			Vector row = dbConnection.data.get(0);
			
			String nickname = row.get(0).toString();
			String email = row.get(1).toString();
			String avatar = row.get(2).toString();
			
			if (tempConnection != null) {
//				tempConnection.setMessage("SERV_BLOCK " + username);
				tempConnection.setMessage("SERV_CHSTATUS " + username + " Offline " + nickname + " " + email + " " + avatar);
			}
			
			connection.setMessage("100 User blocked.");

		} catch (SQLException e) {			
			e.printStackTrace();
			dbConnection.doRollBack();
			return false;
		}
		
		dbConnection.doCommit();
		
		return true;
	}
}
